package api

import (
	"gateway/basic/config"
	__ "gateway/basic/proto"
	"gateway/handler/request"
	"gateway/pkg"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func Login(c *gin.Context) {
	var param request.Login
	if err := c.ShouldBind(&param); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"mes":  "参数错误",
		})
	}
	r, err := config.Usercline.GetUsernameByUsername(c, &__.GetUsernameByUsernameReq{
		Username: param.Username,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"mes":  err.Error(),
		})
		return
	}
	if r.UserId == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"mes":  "用户不存在",
		})
		return
	}
	if r.Password != r.Password {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"mes":  "密码错误",
		})
		return
	}
	token, _ := pkg.NewJWT("user").CreateToken(pkg.CustomClaims{
		ID: uint(r.UserId),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: int64(time.Hour * 5),
		},
	})
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"mes":  "登陆成功",
		"data": token,
	})
}
